package com.hz.filemanager.model;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.hz.filemanager.ad.utils.RemoteConfig;
import com.hz.filemanager.model.clean.ScanBean;
import com.hz.filemanager.model.clean.ThridApp;
import com.hz.filemanager.utils.AppUtils;
import com.hz.filemanager.utils.JsonUtils;
import com.hz.filemanager.utils.LogUtils;
import com.hz.filemanager.utils.Utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;


public class FileDataManager {

    private static final String TAG = FileDataManager.class.getSimpleName();
    private final Gson gson;
    private final AppUtils appUtils;
    private List<ScanBean> scanBeanList;
    public static AppConfig appConfig;

    public List<ScanBean> getScanBeanList() {
        return scanBeanList;
    }




    private static class SingletonInstance{
        private static final FileDataManager INSTANCE = new FileDataManager();
    }

    public static FileDataManager getInstance(){
        return SingletonInstance.INSTANCE;
    }

    private FileDataManager(){
        gson = new Gson();
        appUtils = new AppUtils(Utils.getContext());

        //获取本地存储的配置文件
        String localConfig = JsonUtils.getDatafromFile("remote_config");
        LogUtils.e(TAG, "loacal remote_config = " + localConfig);
        if(localConfig == null || TextUtils.isEmpty(localConfig)){
            //获取assets的app配置文件
            localConfig = getJson(Utils.getContext(), "local_config.json");
            LogUtils.e(TAG, "loacal local_config = " + localConfig);
        }
        updateAppConfig(localConfig);
    }

    public  String getJson(Context context, String fileName) {

        StringBuilder stringBuilder = new StringBuilder();
        AssetManager assetManager = context.getAssets();
        try {
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
            bf.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    public void updateAppConfig(String appConfigJson){

        LogUtils.d(TAG, "appConfigJson : "+ appConfigJson);
        if (TextUtils.isEmpty(appConfigJson)) return;
        try {
            AppConfig config = gson.fromJson(appConfigJson, AppConfig.class);
            if(config != null && config.getFile_Config() != null){
                this.appConfig = config;
                LogUtils.d(TAG, "appConfigBean : "+ config.toString());
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void updateRemoteConfig() {
        String remoteConfig = RemoteConfig.INSTANCE.getDynamicConfigJson();
        if(!TextUtils.isEmpty(remoteConfig)){
            //获取远程配置文件
            updateAppConfig(remoteConfig);
            //保存配置文件
            boolean result = JsonUtils.createJsonFile(remoteConfig, "remote_config");
            LogUtils.e(TAG, "RemoteConfig save  result = " + result );
        }
    }


    public List<ScanBean> scanCleanDatas(){
        scanBeanList = new ArrayList<>();
        Random random = new Random();

        ScanBean scanBean1 = new ScanBean("Residual Junks", 200 + random.nextInt(300), false);
        ScanBean scanBean2 = new ScanBean("APK Files", 200 + random.nextInt(300), false);
        ScanBean scanBean3 = new ScanBean("System Cache", 200 + random.nextInt(300), false);
        ScanBean scanBean4 = new ScanBean("App Cache", 200 + random.nextInt(300), false);
        ScanBean scanBean5 = new ScanBean("App Residual", 200 + random.nextInt(300), false);

        scanBeanList.add(scanBean1);
        scanBeanList.add(scanBean2);
        scanBeanList.add(scanBean3);
        scanBeanList.add(scanBean4);
        scanBeanList.add(scanBean5);
        return scanBeanList;
    }

    public List<ScanBean> scanBoostDatas(){
        scanBeanList = new ArrayList<>();
        ScanBean scanBean1 = new ScanBean("System apps", 0, false);
        ScanBean scanBean2 = new ScanBean("Third-party apps", 0, false);
        scanBeanList.add(scanBean2);
        scanBeanList.add(scanBean1);
        return scanBeanList;
    }

    public String getCurrentTemperature() {
        double temperature =  33 + new Random().nextInt(6) + Math.random();
        return String.format("%.1f", temperature);
    }


    public List<ThridApp> getScanResultList(){

        List<String> packageNameList = generatePackageFixList(getThirdAppList());

        List<ThridApp> fixApps = new ArrayList<>();
        if(packageNameList != null && packageNameList.size() > 0){

            for(String packageName : packageNameList){
                ThridApp thridApp = new ThridApp();
                thridApp.setPackageName(packageName);
                thridApp.setAppName(appUtils.getAppName(packageName));
                thridApp.setAppIcon(appUtils.getAppIconByPackageName(packageName));
                thridApp.setCheck(true);
                fixApps.add(thridApp);
            }
        }
        return fixApps;
    }

    public List<String> getThirdAppList() {

        String selfPackageName = Utils.getContext().getPackageName();
        PackageManager packageManager = Utils.getContext().getPackageManager();
        List<PackageInfo> packageInfoList = packageManager .getInstalledPackages(0);
        List<String> thirdAPP = new ArrayList<>();
        for (int i = 0; i < packageInfoList.size(); i++) {
            PackageInfo pak = (PackageInfo)packageInfoList.get(i);
            //判断是否为系统预装的应用
            if ((pak.applicationInfo.flags & pak.applicationInfo.FLAG_SYSTEM) <= 0) {
                // 第三方应用
                if(!pak.packageName.equals(selfPackageName)){
                    thirdAPP.add( pak.packageName);
                }
                //Log.e("app", "第三方应用----------："+ pak.packageName);
            } else{
                //系统应用
                //Log.e("app", "系统应用："+ pak.packageName);
            }
        }
        return thirdAPP ;
    }

    private List<String> generatePackageFixList(List<String> srcList) {
        //如果源列表数量在 5-25之间，则在5-列表数间取一个随机数
        //如果源列表数量小于等于5，则取源列表数

        int appsize = srcList.size();
        int fixNum = 0;
        if(appsize > 5 ){
            if(appsize>=25){
                fixNum = (5 + new Random().nextInt(20));
            }else{
                fixNum = (5 + new Random().nextInt(appsize-5));
            }
        }else{
            fixNum = appsize;
            //LogUtils.e(TAG,"该用户安装的app数量太少了，非正常用户");
        }

        List<String> fixPackageList = new ArrayList<>();
        //有了修复数，从源列表取出要修复的列表数据
        for(int i=0; i<fixNum; i++){
            fixPackageList.add(srcList.get(i));
        }

        return fixPackageList;
    }
}
